#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @File    : baseapi
# @IDE     : PyCharm
# @Author  : liuxiangui
# @Date    : 2023/12/29 22:09
# @Describe: 
# ==================================================
from requests import Response
from typing import Text
from library.base.request import RequestHttp
from library.log import logger
from config.common_config import MAX_REQUESTERS


def get_response_charset(response: Response) -> Text:
    """
    获取响应内容编码方式
    @param response: 响应体Response
    :return Text
    """
    content_type = response.headers.get('Content-Type', '')
    chart_set = "utf-8"  # 默认编码方式
    if "charset=" in content_type:
        chart_set = content_type.split('=')[-1]
    return chart_set


class BaseAPI(RequestHttp):
    describe = ''
    method = 'post'
    host = ''
    url = ''
    files = ''
    headers = {}
    data = {}
    proxies = {}
    timeout = MAX_REQUESTERS
    verify = False
    isJson = True
    chart_set = "utf-8"

    def run(self) -> Response:
        if self.describe:
            logger.info(self.describe, attach_name="接口描述")
        if self.host + self.url:
            logger.info(self.method.upper() + '\t' + self.host + self.url, attach_name="请求接口")
        if self.headers:
            logger.info(self.headers, attach_name="请求头")
        if self.data:
            logger.info(self.data, attach_name="请求体")
        self.add_request_headers(headers=self.headers)
        # 请求
        resp = self.send(method=self.method,
                         url=self.host + self.url,
                         data=self.data,
                         is_json=self.isJson,
                         timeout=self.timeout,
                         proxies=self.proxies,
                         verify=self.verify,
                         files=self.files
                         )
        self.chart_set = get_response_charset(response=resp)
        return resp
